package com.skywolf.chem.common.excel;

import org.apache.commons.io.IOUtils;
import org.apache.commons.io.LineIterator;
import org.apache.commons.lang3.StringUtils;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;

import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;


public class CsvReader {
    public static ExcelTableIt read( InputStream is) throws Exception{
        return read(is,",");
    }
    public static ExcelTableIt read(InputStream is,String split)throws Exception {
        LineIterator lineIterator = IOUtils.lineIterator(is, "GBK");
        String[] titles = null;


        while (lineIterator.hasNext()) {
            String line = lineIterator.next();
            titles = line.split(split);
            break;
        }
        if(titles==null){
            throw new  IllegalArgumentException("传入的文件header为空.");
        }
        Iterator<ExcelRow> itRow = new CsvIterator(lineIterator, titles, split);
        return new ExcelTableIt(Arrays.asList(titles), itRow);
    }

    private static class CsvIterator  implements Iterator<ExcelRow> {

        private String[] headers;
        private Iterator<String>  content;
        private String split;
        private String[] values=null;
        public CsvIterator(Iterator<String> content, String[] headers,String split) {
            this.content = content;
            this.headers = headers;
            this.split=split;
        }


        @Override
        public boolean hasNext() {
            while (content.hasNext()){
                String line=content.next();
                values=line.split(split,-1);
                if(values.length>=headers.length && !allEmpy(values)){
                    return true;
                }
            }
            values=null;
            return false;
        }

        private boolean allEmpy(String[] values){
            for (String value : values) {
                if(StringUtils.isNotEmpty(value)){
                    return false;//不是空
                }
            }
            return true;
        }
        @Override
        public ExcelRow next() {
            Map<String, String> rowMap = new HashMap<>();
            for (int i1 = 0; i1 < headers.length; i1++) {
                rowMap.put(headers[i1], values[i1]);
            }
            return new ExcelRow(rowMap);
        }
        @Override
        public void remove() {
            throw  new NotImplementedException();
        }
    }

}
